#!/usr/bin/pthon

import os
from errors import NotFoundError
try:
    import Image 
except:
    raise NotFoundError('python-imaging')

def singleton(className):
    def wrapped():
        it =  className.__dict__.get('__it__')
        if it is not None:
            return it

        className.__it__=className()
        return className.__it__
    return wrapped

def uuidgen():
    import uuid
    return str(uuid.uuid4())

def hashgen(s):
    import hashlib
    return hashlib.sha224(s).hexdigest()


'''
Image helper requires to install python-imaging using yum,
or install PIL for other platforms.

See http://www.pythonware.com/products/pil/
''' 
class imageHelper(object):
    def __init__(self, src):

        self.src = src

        try: 
            self.im = Image.open(self.src)
        except:
            raise NotFoundError(self.src)

        
    def format(self):
        return self.im.format.lower()

    def size(self):
        return self.im.size

    def thumbnail(self, xres, yres, quality=80, format='JPEG'):
        import StringIO

        img = self.im
        output = StringIO.StringIO()

        #   When a picture is taller than it is wide, it means the camera was rotated. 
        #   Some cameras can detect this and write that info in the picture's EXIF metadata. 
        #   Some viewers take note of this metadata and display the image appropriately.

        #   PIL can read the picture's metadata, but it does not write/copy metadata when 
        # you save an Image. Consequently, your smart image viewer will not rotate the image 
        # as it did before.
        # 
        # See: http://stackoverflow.com/questions/4228530/pil-thumbnail-is-rotating-my-image
        #
        #exif=dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items() if k in ExifTags.TAGS)
        #if not exif.has_key('Orientation') or not exif['Orientation']:
        #    img=img.rotate(90, expand=True)

        img.thumbnail((xres, yres), Image.ANTIALIAS)
        img.save(output, format, quality=quality)
        return output.getvalue()

if __name__ == '__main__':
    ih = imageHelper('/tmp/a.jpg')
    print ih.format()
    print ih.size()
    with open ('/tmp/b.jpg', 'w') as t:
        print >> t, ih.thumbnail(200, 50)
        t.close()
